﻿Public Class ResultsEntryForm

    Public ReadOnly metaQuery As MetaQuery
    Public ReadOnly pl As SystemBoxSDK.PL.MESSDK.SampleDetail_PL = New SystemBoxSDK.PL.MESSDK.SampleDetail_PL("F9Result")
    Dim frmResults As XtraForm


    Public Overridable Sub ResultsEntryFormExt_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        InitEntries()
        InitToPerform()
        InitSpecTypes()
        InitSpecs()
        InitLots()
        InitUsage()
        InitProduct()
    End Sub

    Public Overridable Sub ResultsEntryFormExt_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        If frmResults IsNot Nothing Then
            frmResults.Close()
        End If
    End Sub

    Public Overridable Sub btnOK_Click(sender As System.Object, e As System.EventArgs) Handles btnOK.Click
        ShowResults()
    End Sub

    Public Overridable Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
        ClearFilters()
    End Sub

    Public Overridable Sub btnClose_Click(sender As System.Object, e As System.EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Public Overridable Sub ResultFormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs)
        Dim dispo As IDisposable
        Dim iSave As ISaveCommand

        ''TestPoint: By design we call dispose on each control that have the dispose Method
        For Each o As Object In frmResults.Controls

            iSave = TryCast(o, ISaveCommand)
            If iSave IsNot Nothing AndAlso iSave.Dataset.HasChanges Then
                If MsgBox(String.Format("You Are About To Lose Your Modifications !{0}Do You Want To Save Now ?", vbCrLf), MsgBoxStyle.YesNo, "* Warning *") = Windows.Forms.DialogResult.Yes Then
                    iSave.SaveCommand()
                End If
            End If
            '
            dispo = TryCast(o, IDisposable)
            If dispo IsNot Nothing Then
                dispo.Dispose()
            End If
        Next
        RemoveHandler frmResults.FormClosed, AddressOf ResultFormClosed

        frmResults = Nothing
    End Sub



    Public Overridable Sub ClearFilters()
        lookUpEntries.ItemIndex = 2 'All
        lookupPerform.ItemIndex = 0 'Both
        lookupSpecs.EditValue = DBNull.Value
        lookupSpecType.EditValue = DBNull.Value
        lookupLots.EditValue = DBNull.Value
        lookupUsage.EditValue = DBNull.Value
        lookupProduct.EditValue = DBNull.Value

        dtLotSampleDateFrom.EditValue = DBNull.Value
        chkLotSampleDateFrom.Checked = False
        dtLotSampleDateTo.EditValue = DBNull.Value
        chkLotSampleDateTo.Checked = False

        rdoAllSpec.Select()
        rdoAllLot.Select()
    End Sub

    Public Overridable Function BuildWhereClause() As String
        Dim strWhere As New System.Text.StringBuilder
        Dim fromDate As Date
        Dim toDate As Date

        'Status Open
        strWhere.Append(String.Format("(Q.QAStatID_FK = '{0}' or Q.QAStat = '{1}')", IdRepository.SAMPLE_HEADER_QASTATUS_O, "O"))


        'Lot Sample Date
        If Me.chkLotSampleDateFrom.Checked OrElse Me.chkLotSampleDateTo.Checked Then
            If Not Me.chkLotSampleDateFrom.Checked Or String.IsNullOrEmpty(dtLotSampleDateFrom.Text) Then
                fromDate = CDate("1960/01/01")
            Else
                fromDate = CDate(Me.dtLotSampleDateFrom.EditValue)
            End If

            If Not Me.chkLotSampleDateTo.Checked Or String.IsNullOrEmpty(dtLotSampleDateTo.Text) Then
                toDate = Date.MaxValue
            Else
                toDate = CDate(Me.dtLotSampleDateTo.EditValue)
            End If

            If strWhere.Length > 0 Then strWhere.Append(" AND ")

            strWhere.Append(String.Format("Q.SampleDT BETWEEN '{0:yyyy/MM/dd}' AND '{1:yyyy/MM/dd}'", fromDate, toDate))
        End If

        'Product Filter
        If Me.rdoProduct.Checked AndAlso Not String.IsNullOrEmpty(lookupProduct.EditValue.ToString()) Then
            If strWhere.Length > 0 Then strWhere.Append(" AND ")
            strWhere.Append(String.Format("Q.PrdId = '{0}'", lookupProduct.EditValue))
        End If

        'Group Specifications
        If rdoAllSpec.Checked Then
            'All Specs
        ElseIf rdoSpec.Checked AndAlso Not String.IsNullOrEmpty(lookupSpecs.EditValue.ToString()) Then
            'Filter Spec
            If strWhere.Length > 0 Then strWhere.Append(" AND ")
            strWhere.Append(String.Format("I.SpecId_FK = '{0}'", lookupSpecs.EditValue))

        ElseIf rdoSpecType.Checked AndAlso Not String.IsNullOrEmpty(lookupSpecType.EditValue.ToString()) Then
            'Filter Spec Type
            If strWhere.Length > 0 Then strWhere.Append(" AND ")
            strWhere.Append(String.Format("I.SpecId_FK IN (SELECT Specification.SpecId FROM Specification WHERE Specification.SpecTypeId_FK = '{0}')", lookupSpecType.EditValue))
        End If


        'Group Lot
        If rdoAllLot.Checked Then
            'All Lots
        ElseIf Me.rdoLot.Checked Then
            'Lot Filter
            If strWhere.Length > 0 Then strWhere.Append(" AND ")
            strWhere.Append(String.Format("I.QAQCInspLotID_FK = '{0}'", lookupLots.EditValue))

        ElseIf Me.rdoUsage.Checked Then
            'Usage Filter
            If strWhere.Length > 0 Then strWhere.Append(" AND ")
            strWhere.Append(String.Format("Q.UsgId = '{0}'", lookupUsage.EditValue))
        End If

        'Entries
        Dim value As Integer = CInt(lookUpEntries.EditValue)
        Select Case value
            Case 0 'Remaining
                If strWhere.Length > 0 Then strWhere.Append(" AND ")
                strWhere.Append("I.WIPStat NOT IN ('C','V')")
                'strWhere.Append(String.Format("a.WIPStatID_FK NOT IN ('{0}','{1}')", IdRepository.SAMPLE_DETAIL_WIPSTATUS_C, IdRepository.SAMPLE_DETAIL_WIPSTATUS_V))
            Case 1 'Completed
                If strWhere.Length > 0 Then strWhere.Append(" AND ")
                strWhere.Append("I.WIPStat IN ('C','V')")
                'strWhere.Append(String.Format("a.WIPStatID_FK IN ('{0}','{1}')", IdRepository.SAMPLE_DETAIL_WIPSTATUS_C, IdRepository.SAMPLE_DETAIL_WIPSTATUS_V))
            Case 2 'All entries
        End Select

        'Compulsory
        value = CInt(lookupPerform.EditValue)
        Select Case value
            Case 1 'Yes
                If strWhere.Length > 0 Then strWhere.Append(" AND ")
                strWhere.Append("I.CompulsoryRep = 1")
            Case 2 'No
                If strWhere.Length > 0 Then strWhere.Append(" AND ")
                strWhere.Append("I.CompulsoryRep = 0")
            Case 0 'Both
        End Select

        Return strWhere.ToString()
    End Function

    Public Overridable Sub ShowResults()
        pl.SQLWhere = BuildWhereClause()
        Me.Cursor = Cursors.WaitCursor

        'Patch hack 1: forcer le close pour valider si un changement a été fait. clieng 2012-10-15
        If frmResults IsNot Nothing Then
            frmResults.Close()
        End If

        If frmResults Is Nothing Then
            frmResults = New XtraForm() With {.MdiParent = Me.ParentForm, .Name = "F9Results", .Text = "F9 Results"}
            Dim aGridExtPL As GridExtPL = New GridExtPL() With {.Dock = DockStyle.Fill, .Pl = pl, .Name = "gridF9Results", .FormCtrlCD = Me.Name, .SecureGrid = True, .LoadWithChilds = False}

            aGridExtPL.GridActionOptionList.Add(New ActionOption("Print", "ACT_00125", "Print", AddressOf PrintResult, True, True))

            AddHandler aGridExtPL.MasterRowCellStyle, AddressOf SampleDetail_MasterRowCellStyle
            AddHandler aGridExtPL.MasterRowStyle, AddressOf SampleDetail_MasterRowStyle
            AddHandler aGridExtPL.MasterRowClick, AddressOf SampleDetail_MasterRowClick
            AddHandler aGridExtPL.ProcessCurrentMasterRecord, AddressOf SampleDetail_ProcessCurrentMasterRecord
            'AddHandler aGridExtPL.MasterCustomRowCellEditForEditing, AddressOf MasterCustomRowCellEditForEditing

            AddHandler frmResults.FormClosed, AddressOf ResultFormClosed
            frmResults.Controls.Add(aGridExtPL)
            frmResults.Show()
        Else
            'Reload data
            CType(frmResults.Controls("gridF9Results"), GridExtPL).ReloadGrid()
            frmResults.Focus()
        End If
        Me.Cursor = Cursors.Default
    End Sub




#Region "   Init Lookup   "

    Public Overridable Sub InitEntries()
        Dim aQueryName As String
        aQueryName = "LOV_F9Entries"
        Dim mqEntries As MetaQuery = metaQuery.GetMetaQueryByName(aQueryName)
        mqEntries.FillResultQuery()

        lookUpEntries.Properties.DataSource = mqEntries.ResultQuery

        lookUpEntries.Properties.ValueMember = mqEntries.ResultQuery.Columns("ValueMember").ToString
        lookUpEntries.Properties.DisplayMember = mqEntries.ResultQuery.Columns("Entries").ToString
        lookUpEntries.Properties.PopulateColumns()
        lookUpEntries.Properties.NullText = String.Empty


        lookUpEntries.Properties.Columns(mqEntries.ResultQuery.Columns("ValueMember").ToString).Visible = False
        lookUpEntries.Properties.BestFitMode = DevExpress.XtraEditors.Controls.BestFitMode.BestFitResizePopup
        lookUpEntries.Properties.SearchMode = DevExpress.XtraEditors.Controls.SearchMode.AutoFilter
        lookUpEntries.Properties.AutoSearchColumnIndex = lookUpEntries.Properties.Columns.IndexOf(lookUpEntries.Properties.Columns("Entries"))
        lookUpEntries.ItemIndex = 2 'All

    End Sub

    Public Overridable Sub InitToPerform()
        Dim aQueryName As String
        aQueryName = "LOV_F9ToPerform"
        Dim mq As MetaQuery = metaQuery.GetMetaQueryByName(aQueryName)
        mq.FillResultQuery()

        lookupPerform.Properties.DataSource = mq.ResultQuery

        lookupPerform.Properties.ValueMember = mq.ResultQuery.Columns("ValueMember").ToString
        lookupPerform.Properties.DisplayMember = mq.ResultQuery.Columns("DisplayMember").ToString
        lookupPerform.Properties.PopulateColumns()
        lookupPerform.Properties.NullText = String.Empty


        lookupPerform.Properties.Columns(mq.ResultQuery.Columns("ValueMember").ToString).Visible = False
        lookupPerform.Properties.Columns(mq.ResultQuery.Columns("DisplayMember").ToString).Caption = String.Empty
        lookupPerform.Properties.BestFitMode = DevExpress.XtraEditors.Controls.BestFitMode.BestFitResizePopup
        lookupPerform.Properties.SearchMode = DevExpress.XtraEditors.Controls.SearchMode.AutoFilter
        lookupPerform.Properties.AutoSearchColumnIndex = lookUpEntries.Properties.Columns.IndexOf(lookUpEntries.Properties.Columns("DisplayMember"))
        lookupPerform.ItemIndex = 0 'Both
    End Sub

    Public Overridable Sub InitSpecs()
        lookupSpecs.Text = String.Empty
        lookupSpecs.QueryName = "LOV_F9Specification"
        lookupSpecs.InitMetaQuery()
    End Sub

    Public Overridable Sub InitSpecTypes()
        lookupSpecType.Text = String.Empty
        lookupSpecType.QueryName = "LOV_F9SpecificationTypes"
        lookupSpecType.InitMetaQuery()
    End Sub

    Public Overridable Sub InitLots()
        lookupLots.Text = String.Empty
        lookupLots.QueryName = "LOV_F9Lots"
        lookupLots.InitMetaQuery()
    End Sub

    Public Overridable Sub InitUsage()
        lookupUsage.Text = String.Empty
        lookupUsage.QueryName = "LOV_F9Usage"
        lookupUsage.InitMetaQuery()
    End Sub

    Public Overridable Sub InitProduct()
        'lookupProduct.Text = String.Empty
        lookupProduct.ErrorText = String.Empty
        lookupProduct.QueryName = "LOV_F9Product"
        lookupProduct.InitMetaQuery()
    End Sub

#End Region


#Region "   Set Default Value on Delete Key Down  "

    Public Overridable Sub lookUpEntries_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles lookUpEntries.KeyDown
        If (e.KeyCode = Keys.Delete) Then
            Me.lookUpEntries.ItemIndex = 0 'Remainning
        End If
    End Sub

    Public Overridable Sub lookupPerform_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles lookupPerform.KeyDown
        If (e.KeyCode = Keys.Delete) Then
            Me.lookupPerform.ItemIndex = 1 'Yes
        End If
    End Sub

    Public Overridable Sub lookupSpecs_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs)
        If (e.KeyCode = Keys.Delete) Then
            Me.lookupSpecs.EditValue = DBNull.Value
        End If
    End Sub

    Public Overridable Sub lookUpSpecType_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs)
        If (e.KeyCode = Keys.Delete) Then
            Me.lookupSpecType.EditValue = DBNull.Value
        End If
    End Sub

    Public Overridable Sub lookupLots_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs)
        If (e.KeyCode = Keys.Delete) Then
            Me.lookupLots.EditValue = DBNull.Value
        End If
    End Sub

    Public Overridable Sub lookupUsage_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs)
        If (e.KeyCode = Keys.Delete) Then
            Me.lookupUsage.EditValue = DBNull.Value
        End If
    End Sub

    Public Overridable Sub lookupProduct_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs)
        If (e.KeyCode = Keys.Delete) Then
            Me.lookupProduct.EditValue = DBNull.Value
        End If
    End Sub

#End Region


#Region "   Filters Event   "

    Public Overridable Sub chkLotSampleDateFrom_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles chkLotSampleDateFrom.CheckedChanged
        If chkLotSampleDateFrom.Checked Then
            dtLotSampleDateFrom.Enabled = True
        Else
            dtLotSampleDateFrom.EditValue = DBNull.Value
            dtLotSampleDateFrom.Enabled = False
        End If
    End Sub

    Public Overridable Sub chkLotSampleDateTo_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles chkLotSampleDateTo.CheckedChanged
        If chkLotSampleDateTo.Checked Then
            dtLotSampleDateTo.Enabled = True
        Else
            dtLotSampleDateTo.EditValue = DBNull.Value
            dtLotSampleDateTo.Enabled = False
        End If
    End Sub


    Public Overridable Sub rdoAllSpec_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rdoAllSpec.CheckedChanged
        If rdoAllSpec.Checked Then
            'Reset & Disable Spec Type dropdownlist
            lookupSpecType.EditValue = DBNull.Value
            lookupSpecType.Enabled = False

            'Reset & Disable Spec dropdownlist
            lookupSpecs.EditValue = DBNull.Value
            lookupSpecs.Enabled = False
        End If
    End Sub

    Public Overridable Sub rdoSpec_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rdoSpec.CheckedChanged
        If rdoSpec.Checked Then
            lookupSpecs.Enabled = True
            lookupSpecs.Focus()

            'Reset & Disable Spec Type dropdownlist
            lookupSpecType.EditValue = DBNull.Value
            lookupSpecType.Enabled = False
        End If
    End Sub

    Public Overridable Sub rdoSpecType_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rdoSpecType.CheckedChanged
        If rdoSpecType.Checked Then
            lookupSpecType.Enabled = True
            lookupSpecType.Focus()

            'Reset & Disable Spec dropdownlist
            lookupSpecs.EditValue = DBNull.Value
            lookupSpecs.Enabled = False
        End If
    End Sub


    Public Overridable Sub rdoAllLot_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rdoAllLot.CheckedChanged
        If rdoAllLot.Checked Then
            'Reset & Disable Lot dropdownlist
            lookupLots.EditValue = DBNull.Value
            lookupLots.Enabled = False

            'Reset & Disable Usage dropdownlist
            lookupUsage.EditValue = DBNull.Value
            lookupUsage.Enabled = False

            'Reset & Disable Product dropdownlist
            lookupProduct.EditValue = DBNull.Value
            lookupProduct.Enabled = False
        End If
    End Sub

    Public Overridable Sub rdoLot_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rdoLot.CheckedChanged
        If rdoLot.Checked Then
            lookupLots.Enabled = True
            lookupLots.Focus()

            'Reset & Disable Usage dropdownlist
            lookupUsage.EditValue = DBNull.Value
            lookupUsage.Enabled = False

            'Reset & Disable Product dropdownlist
            lookupProduct.EditValue = DBNull.Value
            lookupProduct.Enabled = False
        End If
    End Sub

    Public Overridable Sub rdoUsage_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rdoUsage.CheckedChanged
        If rdoUsage.Checked Then
            lookupUsage.Enabled = True
            lookupUsage.Focus()

            'Reset & Disable Lot dropdownlist
            lookupLots.EditValue = DBNull.Value
            lookupLots.Enabled = False

            'Reset & Disable Product dropdownlist
            lookupProduct.EditValue = DBNull.Value
            lookupProduct.Enabled = False
        End If
    End Sub

    Public Overridable Sub rdoProduct_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rdoProduct.CheckedChanged
        If rdoProduct.Checked Then
            lookupProduct.Enabled = True
            lookupProduct.Focus()

            'Reset & Disable Lot dropdownlist
            lookupLots.EditValue = DBNull.Value
            lookupLots.Enabled = False

            'Reset & Disable Usage dropdownlist
            lookupUsage.EditValue = DBNull.Value
            lookupUsage.Enabled = False
        End If
    End Sub

#End Region

End Class